package com.xl.utils.file;

import cn.hutool.core.util.ArrayUtil;
import com.xl.utils.enums.FileTimeZoneEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 文件处理工具类
 *
 * @author netshark.kfd
 */
@Slf4j
public class FileUtils {
    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    //时间格式化标准
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据文件全路径判断文件是否存在
     *
     * @param path 全路径
     * @return
     */
    public static boolean exist(String path) {
        File file = getFile(path);
        return file.exists();
    }

    /**
     * 判断文件是否存在
     * 存在返回文件
     *
     * @param path 根据文件全路径判断文件是否存在
     * @return
     */
    public static File existRetFile(String path) {
        File file = getFile(path);
        if (file.exists()) {
            return file;
        }
        return null;
    }

    /**
     * 判断文件夹存在
     * 获取文件夹里面所有的文件
     * 不递归获取
     *
     * @param path
     */
    public static List<File> existDirGetChildFiles(String path) {
        return getDirFiles(path, false);
    }

    /**
     * 判断文件夹存在
     * 获取文件夹里面所有的文件
     * recursion 为false 不递归获取 为true递归获取文件夹下的文件
     *
     * @param path
     * @param recursion
     * @return
     */
    public static List<File> existDirGetChildFiles(String path, boolean recursion) {
        return getDirFiles(path, recursion);
    }


    private static List<File> getDirFiles(String path, boolean recursion) {
        File dirFile = existRetFile(path);
        if (Objects.isNull(dirFile) || dirFile.isFile()) {
            return Lists.newArrayList();
        }
        File[] childrenFiles = dirFile.listFiles();
        if (ArrayUtil.isEmpty(childrenFiles)) {
            return Lists.newArrayList();
        }
        List<File> files = new ArrayList<>();
        for (File file : childrenFiles) {
            if (file.isFile()) {
                files.add(file);
            } else {
                if (!recursion) {
                    continue;
                } else {
                    List<File> fileList = getDirFiles(file.getPath(), recursion);
                    if (!CollectionUtils.isEmpty(fileList)) {
                        files.addAll(fileList);
                    }
                }
            }
        }
        return files;
    }

    /**
     * 根据path得到文件（File）
     *
     * @param path
     * @return
     */
    private static File getFile(String path) {
        File file = new File(path);
        return file;
    }

    /**
     * 按照时间类型倒序排序
     *
     * @param files
     * @param fileTimeZone
     * @return
     * @see
     */
    public static List<Map.Entry<String, List<File>>> sortedByTimeDesc(List<File> files, FileTimeZoneEnum fileTimeZone) {
        Map<String, List<File>> treeMap = getFileListMap(files, fileTimeZone);
        List<Map.Entry<String, List<File>>> treeList = new ArrayList<>(treeMap.entrySet());
        treeList.sort((o1, o2) -> {
            Date o1parse = null;
            Date o2parse = null;
            try {
                o1parse = dateFormat.parse(o1.getKey());
                o2parse = dateFormat.parse(o2.getKey());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            int compare = o2parse.compareTo(o1parse);
            return compare;
        });
        return treeList;
    }

    /**
     * key是文件的时间,value是文件本身
     *
     * @param files
     * @param fileTimeZone
     * @return
     * @see FileTimeZoneEnum
     */
    private static Map<String, List<File>> getFileListMap(List<File> files, FileTimeZoneEnum fileTimeZone) {
        Map<String, List<File>> treeMap = new TreeMap<>();
        for (File file : files) {
            BasicFileAttributes attr = null;
            try {
                Path path = file.toPath();
                attr = Files.readAttributes(path, BasicFileAttributes.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (Objects.isNull(attr)) {
                continue;
            }
            // 创建时间
            Instant instant = null;
            switch (fileTimeZone) {
                case CREATE_TIME:
                    instant = attr.creationTime().toInstant();
                    break;
                case LAST_MODIFIED_TIME:
                    instant = attr.lastModifiedTime().toInstant();
                    break;
                case LAST_ACCESS_TIME:
                    instant = attr.lastAccessTime().toInstant();
                    break;
                default:
                    throw new RuntimeException("时间类型错误");
            }
            String time = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(instant);
            if (treeMap.containsKey(time)) {
                List<File> fileList = treeMap.get(time);
                fileList.add(file);
                treeMap.put(time, fileList);
                continue;
            }
            ArrayList<File> arrayList = new ArrayList<>();
            arrayList.add(file);
            treeMap.put(time, arrayList);
        }
        return treeMap;
    }


    /**
     * 按照时间类型顺序排序
     *
     * @param files
     * @param fileTimeZone
     * @return
     * @see FileTimeZoneEnum
     */
    public static List<Map.Entry<String, List<File>>> sortedByTimeAsc(List<File> files, FileTimeZoneEnum fileTimeZone) {
        Map<String, List<File>> treeMap = getFileListMap(files, fileTimeZone);
        List<Map.Entry<String, List<File>>> treeList = new ArrayList<>(treeMap.entrySet());
        treeList.sort((o1, o2) -> {
            Date o1parse = null;
            Date o2parse = null;
            try {
                o1parse = dateFormat.parse(o1.getKey());
                o2parse = dateFormat.parse(o2.getKey());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            int compare = o1parse.compareTo(o2parse);
            return compare;
        });
        return treeList;
    }

    /**
     * 转换文件大小
     */
    public static String FormatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS == 0) {
            fileSizeString = "0.00B";
        } else {
            if (fileS < 1024) {
                fileSizeString = df.format((double) fileS) + "B";
            } else if (fileS < 1048576) {
                fileSizeString = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                fileSizeString = df.format((double) fileS / 1048576) + "MB";
            } else {
                fileSizeString = df.format((double) fileS / 1073741824) + "GB";
            }
        }
        return fileSizeString;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource) {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, "..")) {
            return false;
        }

        // 检查允许下载的文件规则
        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 返回文件名
     *
     * @param filePath 文件
     * @return 文件名
     */
    public static String getName(String filePath) {
        if (null == filePath) {
            return null;
        }
        int len = filePath.length();
        if (0 == len) {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1))) {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--) {
            c = filePath.charAt(i);
            if (isFileSeparator(c)) {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    /**
     * 是否为Windows或者Linux（Unix）文件分隔符<br>
     * Windows平台下分隔符为\，Linux（Unix）为/
     *
     * @param c 字符
     * @return 是否为Windows或者Linux（Unix）文件分隔符
     */
    public static boolean isFileSeparator(char c) {
        return SLASH == c || BACKSLASH == c;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 计算文件的MD5值
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte[] buffer = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            return new BigInteger(1, digest.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void downloadFile(String filePath, String url, String packageName, String fileMD5) {
        log.info("网管上传的文件为-{}", packageName);
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String fullPath = filePath + "/" + packageName;
        File file = new File(fullPath);
        if (!(file.exists() && fileMD5.equals(FileUtils.getFileMD5(file)))) {
            //从网管下载
            downloadFromNetshark(url, fullPath);
            log.info("mpu下载文件成功-{}", fullPath);
        }
    }


    public static void downloadFromNetshark(String url, String fullPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            // 构造URL
            URL u = new URL(url);
            // 打开连接
            URLConnection conn = u.openConnection();
            int fileSize = conn.getContentLength();
            // 输入流
            inStream = conn.getInputStream();
            //1K的数据缓冲
            byte[] buffer = new byte[1024];
            // 读取到的数据长度
            int length, curSize = 0, readNum = 0;

            fs = new FileOutputStream(fullPath, false); //false：覆盖文件,true:在原有文件后追加
            //开始读取
            fileSize /= 100;  //百分比
            while ((length = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, length);
                ++readNum;
                curSize += length;
                if (readNum % 100 == 0) {
                    log.info("文件下载进度：======== {}, {}%", curSize, curSize / fileSize);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭所有连接
            if (null != fs) {
                try {
                    fs.flush();
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
